/**
 * 
 */
package com.kunbo.cn.service.impl.core.inventory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.kunbo.cn.dao.core.inventory.OrganizationDao;
import com.kunbo.cn.entity.core.inventory.Organization;
import com.kunbo.cn.service.core.inventory.OrganizationService;
import com.kunbo.cn.util.tree.OrganizationTreeUtil;

/**
 *
 * @author bjl  
 * @date 2019年2月27日 
 */
@Service
public class OrganizationServiceImpl  implements OrganizationService{
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Autowired
	private OrganizationDao organizeDao;

  
	@Autowired
    private JdbcTemplate jdbcTemplate;
	
	

	@Override
	public void save(Organization organize) {
		organize.setCreateTime(sdf.format(new Date()));
		organizeDao.save(organize);
	}

	@Override
	public void update(Organization organize) {
		organize.setLastModifiedTime(sdf.format(new Date()));
		organizeDao.save(organize);
	}
	
	@Override
	public void updateValidState(Organization organize) {
		organizeDao.save(organize);
	}
	

	@Override
	public void delete(String id) {
		organizeDao.delete(id);
	}

	@Override
	public Organization findById(String id) {
		return organizeDao.findOne(id);
	}

	@Override
	public List<Organization> getOrganizationTreeList() {
		List<Organization> list = (List<Organization>) organizeDao.findAll();
		List data = new OrganizationTreeUtil().data(list);
		return data;
	}

	@Override
	public Page<Organization> findOrganizationByTitle(String title, Integer pageNo, Integer pageSize) {
		Pageable pageable = new PageRequest(pageNo-1, pageSize);
        Specification<Organization> confusion=new Specification<Organization>() {
            @Override
            public Predicate toPredicate(Root<Organization> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
            	List<Predicate> predicates = new ArrayList<>();
            	if(!"".equals(title)) {
            		predicates.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
            	}
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return organizeDao.findAll(confusion, pageable);
		
	}
}
